package com.ji.kryo;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.ji.module.Person;
import com.ji.module.School;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

//循环依赖无法解决
//不支持 类属性增量
//不支持 子类
public class KryoTool {

    //循环依赖无法解决
    //不支持 类属性增量
    private static byte[] serialize(Object obj) {
        byte[] bytes;
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            //获取kryo对象
            Kryo kryo = new Kryo();
            Output output = new Output(outputStream);
            kryo.writeObject(output, obj);
            bytes = output.toBytes();
            output.flush();
            output.close();
        } catch (Exception ex) {
            throw new RuntimeException("kryo serialize error" + ex.getMessage());
        }
        return bytes;
    }

    private static <T> T deSerialize(byte[] bytes, Class<T> t) {
        T object;
        try (ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes)) {
            Kryo kryo = new Kryo();
            Input input = new Input(inputStream);
            object = kryo.readObject(input, t);
            input.close();
        } catch (Exception ex) {
            throw new RuntimeException("kryo serialize error" + ex.getMessage());
        }
        return object;
    }


    public static void main(String[] args) throws IOException {
        School school = new School();
        school.setAddress("南京");
        school.setName("南大");
        Person person = new Person(21, "小王");
        Person person2 = new Person(22, "小李");
        // person.setSchool(school);
        // person2.setSchool(school);
        //循环依赖无法解决
        //不支持 类属性增量
        List<Person> list = new ArrayList<>();
        list.add(person);
        list.add(person2);
        school.setStudents(list);
        byte[] bytes = KryoTool.serialize(school);
        System.out.println(KryoTool.deSerialize(bytes, School.class));


    }
}
